using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Health : MonoBehaviour {

	public GameObject healthBar;

	public float initHPs = 1f;

	public float hps = 1f;

	public int pointValue = 1;

	float burnDamage = 0;
	float burnTime = 0;

	float burnBaseTime = 10f;

	public bool hasHealthBar = false;

	public GameObject spawnOnDeath;
	public int numToSpawn = 0;

	public AudioClip deathSound;
	public AudioClip hurtSound;
	public float deathVolume = 0.5f;

	public GameObject debris;

	float invulTimer = 0.25f;

	void Awake() {
		if(gameObject.layer == 8) {
			initHPs = GameManager.Instance.maxHPs;
		}

		hps = initHPs;

		if(hasHealthBar) {
			GameObject hbgo = (GameObject)Instantiate(healthBar);
			hbgo.GetComponent<Healthbar>().target = this.transform;
		}

	}

	public bool IsBurning() {
		return burnTime > 0;
	}

	void Update() {
		invulTimer -= Time.deltaTime;

		if(Input.GetKeyDown("["))
			Die ();

		if(gameObject.layer == 8) {
			float hpDiff = GameManager.Instance.maxHPs - initHPs;
			initHPs = GameManager.Instance.maxHPs;
			hps += hpDiff;
		}


		if(burnTime > 0) {
			float d = burnDamage/burnBaseTime * Time.deltaTime;
			burnTime -= Time.deltaTime;
			TakeDamage(d, false, true);
		}

		if(gameObject.layer == 8) {
			hps += GameManager.Instance.regenerationRate*Time.deltaTime;
			if(hps > initHPs)
				hps = initHPs;
		}
	}

	public void TakeDamage(float amt, bool isNewBurnDamage=false, bool isExistingBurnDamage=false) {
		if(isNewBurnDamage) {
			if(burnDamage/burnBaseTime*burnTime < amt) {
				burnDamage = amt;
				burnTime = burnBaseTime;
			}
			return;
		}

		if(invulTimer > 0)
			return;

		if(isExistingBurnDamage==false && hurtSound != null)
			AudioSource.PlayClipAtPoint(hurtSound, Vector3.zero, 0.25f);

		if(gameObject.name == "Player")
			ShakeTracker.Instance.Bump();

		hps -= amt;
		if(hps <= 0) {
			Die();
		}

	}

	public void Die() {
		MonsterGenerator mg = GetComponent<MonsterGenerator>();
		if(mg != null) {
			Health mHealth = mg.monsterPrefab.GetComponent<Health>();
			if(mHealth != null) {
				int mPoints = mHealth.pointValue;

				mPoints *= mg.numSpawns * mg.monsterPerSpawn;

				mPoints *= 2;

				GameManager.Instance.score += (int)(mPoints * GameManager.Instance.DifficultyExponential());
			}
		}

		GameManager.Instance.score += (int)(pointValue * GameManager.Instance.DifficultyExponential());

		if(spawnOnDeath != null) {
			for(int i=0; i<numToSpawn;i++) {
				Instantiate(spawnOnDeath, transform.position, transform.rotation);
			}
		}

		if(deathSound != null)
			AudioSource.PlayClipAtPoint(deathSound, Vector3.zero, deathVolume);

		if(gameObject.layer == 10) {
			GameManager.Instance.totalEnemiesKilled++;
		}

		if(debris != null)
			Instantiate(debris, transform.position, Quaternion.identity);

		Destroy(gameObject);
	}

}
